package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.security.auth.login.LoginException;
import java.time.LocalDateTime;
import java.util.HashMap;

/*
 * 用户的service
 * service层的作用：
 *   调用mapper层的方法查询数据库，如果需要将查询到的数据进行逻辑处理就在service层处理
 *   返回结果给Controller层
 * */
@Service
@Slf4j
public class UserServiceImp implements UserService {
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;
    public static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 用户登录
     *
     * @param userLoginDTO
     * @return user
     * @info 接收前端传递过来的请求体参数userLoginDTO，service层再去调用Mapper层的方法去数据库中根据openid查询user用户  Service->Mapper
     */
    @Override
    public User userWxLogin(UserLoginDTO userLoginDTO) {
        // 调用getUserOpenId()方法，获取openid
        String openid = getUserOpenId(userLoginDTO);
        // 判断openid是否为空，如果为空则表示登录失败，抛出异常
        if (openid == null) throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        // 调用userMapper层的getUserByOpenid(openid)根据openid查询user用户然后判断当前用户是否为新用户，如果是新用户则自动完成注册
        User user = userMapper.getUserByOpenid(openid);
        if (user == null) user = User.builder().openid(openid).createTime(LocalDateTime.now()).build();
        Long id = userMapper.insertUser(user);
        return user;
    }

    /*调用微信接口服务，获取当前用户的openid*/
    private String getUserOpenId(UserLoginDTO userLoginDTO) {
        HashMap<String, String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", userLoginDTO.getCode());
        map.put("grant_type", "authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN_URL, map);
        String openid = JSON.parseObject(json).getString("openid");
        return openid;
    }
}
